package com.xaw4.applejack;

import javax.microedition.khronos.opengles.GL10;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.RectF;
import android.opengl.GLU;
import android.util.Log;

import com.badlogic.gamedev.tools.Font;
import com.badlogic.gamedev.tools.Font.FontStyle;
import com.badlogic.gamedev.tools.Font.Text;
import com.badlogic.gamedev.tools.GameActivity;
import com.badlogic.gamedev.tools.Mesh;
import com.badlogic.gamedev.tools.Mesh.PrimitiveType;
import com.badlogic.gamedev.tools.Texture;
import com.badlogic.gamedev.tools.Texture.TextureFilter;
import com.badlogic.gamedev.tools.Texture.TextureWrap;
import com.xaw4.applejack.simulation.Apple;
import com.xaw4.applejack.simulation.Cart;
import com.xaw4.applejack.simulation.Simulation;

public class Renderer 
{
	RectF playfield;
	Mesh appleMesh;
	Texture appleTexture;
	Mesh cartMesh;
	
	Mesh backgroundMesh;
	Texture backgroundTexture;
	
	Font font;
	Text text;
	
	int lastScore = 0;
	int lastDrops = 0;
	
	public Renderer( GL10 gl, GameActivity activity, RectF field )
	{	
		playfield=field;
		try
		{
			appleMesh = new Mesh(gl, 4, false, true, false);
			appleMesh.texCoord(0, 0);
			appleMesh.vertex( - Apple.APPLE_RADIUS, + Apple.APPLE_RADIUS, Simulation.APPLE_LAYER);
			appleMesh.texCoord(1, 0);
			appleMesh.vertex( + Apple.APPLE_RADIUS, + Apple.APPLE_RADIUS, Simulation.APPLE_LAYER);
			appleMesh.texCoord(1, 1);
			appleMesh.vertex( + Apple.APPLE_RADIUS, - Apple.APPLE_RADIUS, Simulation.APPLE_LAYER);
			appleMesh.texCoord(0, 1);
			appleMesh.vertex( - Apple.APPLE_RADIUS, - Apple.APPLE_RADIUS, Simulation.APPLE_LAYER);
			
			cartMesh = new Mesh(gl, 4, true, false, false);
			cartMesh.color(0.5f, 0.9f, 0.9f, 1);
			cartMesh.vertex(-Cart.cartWidth/2, 0, Simulation.CART_LAYER);
			cartMesh.color(0.5f, 0.9f, 0.9f, 1);
			cartMesh.color(1, 0.9f, 0.9f, 1);
			cartMesh.vertex(+Cart.cartWidth/2, 0, Simulation.CART_LAYER);
			cartMesh.color(0.5f, 0.9f, 0.9f, 1);
			cartMesh.color(1, 0.9f, 0.9f, 1);
			cartMesh.vertex(+Cart.cartWidth/2, -Cart.cartWidth/5, Simulation.CART_LAYER);
			cartMesh.color(0.5f, 0.9f, 0.9f, 1);
			cartMesh.color(1, 0.9f, 0.9f, 1);
			cartMesh.vertex(-Cart.cartWidth/2, -Cart.cartWidth/5, Simulation.CART_LAYER);
			
			backgroundMesh = new Mesh(gl, 4, false, true, false);
			backgroundMesh.texCoord(0, 0);
			backgroundMesh.vertex( field.left, field.top, 0);
			backgroundMesh.texCoord(1, 0);
			backgroundMesh.vertex( field.right, field.top, 0);
			backgroundMesh.texCoord(1, 1);
			backgroundMesh.vertex( field.right, field.bottom, 0);
			backgroundMesh.texCoord(0, 1);
			backgroundMesh.vertex( field.left, field.bottom, 0);
			
		}
		catch( Exception ex )
		{
			Log.d( "Apple Jack", "couldn't load meshes" );
			throw new RuntimeException( ex );
		}
		
		try
		{					
			Bitmap bitmap = BitmapFactory.decodeStream( activity.getAssets().open( "ball.jpg" ) );
			appleTexture = new Texture( gl, bitmap, TextureFilter.MipMap, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge );
			bitmap.recycle();
			
			bitmap = BitmapFactory.decodeStream( activity.getAssets().open( "backgrnd.jpg" ) );
			backgroundTexture = new Texture( gl, bitmap, TextureFilter.MipMap, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge );
			bitmap.recycle();
		}
		catch( Exception ex )
		{
			Log.d( "Apple Jack", "couldn't load textures" );
			throw new RuntimeException( ex );
		}
		
		font = new Font( gl, activity.getAssets(), "font.ttf", 16, FontStyle.Plain );
		text = font.newText( gl );
		
	}
	
	public void render( GL10 gl, GameActivity activity, Simulation simulation )
	{		
		gl.glClear( GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT );
		gl.glViewport( 0, 0, activity.getViewportWidth(), activity.getViewportHeight() );					
		
		gl.glEnable( GL10.GL_TEXTURE_2D );	
		
		renderBackground( gl );		
		
		renderApples(gl, simulation);
		
		renderCart(gl, simulation.cart, activity);
		
		renderText(gl, activity, simulation);
		
		
//		
//		gl.glDisable( GL10.GL_DITHER );
//		gl.glEnable( GL10.GL_DEPTH_TEST );
//		gl.glEnable( GL10.GL_CULL_FACE );		
//		
//		setProjectionAndCamera( gl, simulation.ship, activity );
//		setLighting( gl );
//					
//		renderShip( gl, simulation.ship, activity );
//		renderInvaders( gl, simulation.invaders );
//		
//		gl.glDisable( GL10.GL_TEXTURE_2D );
//		renderBlocks( gl, simulation.blocks );
//		
//		gl.glDisable( GL10.GL_LIGHTING );
//		renderShots( gl, simulation.shots );
//		
//		gl.glEnable( GL10.GL_TEXTURE_2D );
//		renderExplosions( gl, simulation.explosions );
//		
//		gl.glDisable( GL10.GL_CULL_FACE );
//		gl.glDisable( GL10.GL_DEPTH_TEST );
//	
//		set2DProjection(gl, activity);
//		
//		gl.glEnable( GL10.GL_BLEND );
//		gl.glBlendFunc( GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA );
//		gl.glTranslatef( 0, activity.getViewportHeight(), 0 );
//		if( simulation.ship.lives != lastLives || simulation.score != lastScore || simulation.wave != lastWave )
//		{
//			text.setText( "lives: " + simulation.ship.lives + " wave: " + simulation.wave + " score: " + simulation.score );
//			lastLives = simulation.ship.lives;
//			lastScore = simulation.score;
//			lastWave = simulation.wave;
//		}
//		text.render();
//		gl.glDisable( GL10.GL_BLEND);
//		gl.glDisable( GL10.GL_TEXTURE_2D );
//		
//		invaderAngle+=activity.getDeltaTime() * 90;
//		if( invaderAngle > 360 )
//			invaderAngle -= 360;
	}	

	private void renderText(GL10 gl, GameActivity activity, Simulation simulation) {
		gl.glEnable( GL10.GL_BLEND );
		gl.glBlendFunc( GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA );
		float pheight = -playfield.height();
		float vheight = activity.getViewportHeight();
		float translateRatio =(pheight/vheight);
		float fontheight = font.getLineHeight();
		float halfLine = (fontheight/2);
		float lineMiddle=( halfLine* translateRatio);
		float h=playfield.top - lineMiddle;
		gl.glTranslatef( 0, h, 0 );
		gl.glScalef(translateRatio, translateRatio, 1);
		if( simulation.drops != lastDrops || simulation.score != lastScore )
		{
			text.setText( " score: " + simulation.score + " drops: " + simulation.drops );
			lastDrops = simulation.drops;
			lastScore = simulation.score;
		}
		text.render();
		
	}

	private void renderBackground( GL10 gl )
	{
		set2DProjection(gl);
		backgroundTexture.bind();
		backgroundMesh.render(PrimitiveType.TriangleFan);
	}
	
	private void renderApples(GL10 gl, Simulation sim){
		set2DProjection(gl);
		appleTexture.bind();
		gl.glEnable( GL10.GL_BLEND );
		gl.glBlendFunc( GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA );
		for (Apple apple : sim.apples) {
			gl.glPushMatrix();
			gl.glTranslatef( apple.position.x, apple.position.y, apple.position.z );
			
			appleMesh.render(PrimitiveType.TriangleFan);
			gl.glPopMatrix();
		}
		
	}
	
//	private void setProjectionAndCamera( GL10 gl, GameActivity activity )
//	{
//		gl.glMatrixMode( GL10.GL_PROJECTION );
//		gl.glLoadIdentity();
//		float aspectRatio = (float)activity.getViewportWidth() / activity.getViewportHeight();
//		GLU.gluPerspective( gl, 67, aspectRatio, 1, 1000 );					
//		
//		gl.glMatrixMode( GL10.GL_MODELVIEW );
//		gl.glLoadIdentity();
////		GLU.gluLookAt( gl, ship.position.x, 6, 2, ship.position.x, 0, -4, 0, 1, 0 );
//	}
	
	private void set2DProjection( GL10 gl)
	{
		gl.glMatrixMode( GL10.GL_PROJECTION );
		gl.glLoadIdentity();
		GLU.gluOrtho2D( gl, playfield.left,playfield.right, playfield.bottom, playfield.top );
		gl.glMatrixMode( GL10.GL_MODELVIEW );
		gl.glLoadIdentity();
	}
	
//	float[] direction = { 1, 0.5f, 0, 0 };	
//	private void setLighting( GL10 gl )
//	{
//		gl.glEnable( GL10.GL_LIGHTING );
//		gl.glEnable( GL10.GL_LIGHT0 );				
//		gl.glLightfv( GL10.GL_LIGHT0, GL10.GL_POSITION, direction, 0 );
//		gl.glEnable( GL10.GL_COLOR_MATERIAL );		
//	}
	
	private void renderCart( GL10 gl, Cart cart, GameActivity activity )
	{
		set2DProjection(gl);
		//shipTexture.bind();
		gl.glPushMatrix();
		gl.glTranslatef( cart.position.x, cart.position.y, cart.position.z );
		//gl.glRotatef( 45 * (-activity.getAccelerationOnYAxis() / 5), 0, 0, 1 );
		//gl.glRotatef( 180, 0, 1, 0 );
		cartMesh.render(PrimitiveType.TriangleFan);
		gl.glPopMatrix();
	}
	
	
	
	
	public void dispose( )
	{
		appleTexture.dispose();
		backgroundTexture.dispose();
		font.dispose();
		text.dispose();
		
		appleMesh.dispose();
		cartMesh.dispose();
		backgroundMesh.dispose();
	}
}
